const crypto = require('crypto')
const jwt = require('jsonwebtoken')
const { PRIVATE_KEY } = require('./constant')

// 判断参数是否为对象
function isObject(o) {
	return Object.prototype.toString.call(o) === '[object object]'
}

function md5(s) {
	// 参数需要为String类型
	return crypto.createHash('md5')
		.update(String(s)).digest('hex')
}

// 解析token
function decoded(req) {
	// let token = req.get('Authorization')
	// if(token.indexOf('Bearer') >= 0 ) {
	// 	token = token.replace('Bearer', '')
	// }
	// return jwt.verify(token, PRIVATE_KEY)
	const authorization = req.get('Authorization')
  let token = ''
  if (authorization.indexOf('Bearer') >= 0) {
    token = authorization.replace('Bearer ', '')
  } else {
    token = authorization
  }
  return jwt.verify(token, PRIVATE_KEY)
}

module.exports = {
	md5,
	decoded,
	isObject
}